package com.open.capacity.finance.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.open.capacity.finance.util.FileUtil;
import com.open.capacity.user.model.SysCompany;
import com.open.capacity.user.model.SysDepartment;
import com.open.capacity.user.service.SysCompanyService;
import com.open.capacity.user.service.SysDepartmentService;
import com.open.capacity.utils.DateUtil;
import com.open.capacity.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.open.capacity.commons.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.commons.CodeEnum;

import java.util.*;

import org.apache.commons.collections4.MapUtils;

import com.open.capacity.finance.entity.SourceBaseUsecar;
import com.open.capacity.finance.dao.SourceBaseUsecarDao;
import com.open.capacity.finance.service.SourceBaseUsecarService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


@Slf4j
@Service
public class SourceBaseUsecarServiceImpl implements SourceBaseUsecarService {

    @Autowired
    private SourceBaseUsecarDao sourceBaseUsecarDao;

    @Autowired
    private SysCompanyService companyService;

    @Autowired
    private SysDepartmentService departmentService;


    /**
     * 保存到数据库
     *
     * @param url
     */
    @Transactional
    public int save2db(String companyId, Integer kjnd, Integer importway, String url) {
        MultipartFile multipartFile = FileUtil.toMultipartFile("usecarXls", url);
        ImportParams params = new ImportParams();
        params.setTitleRows(0); //前面header空几行
        params.setHeadRows(1);
        // params.setTitleRows(0);
        // 开启excel校验
        params.setNeedVerify(false);

        List<SourceBaseUsecar> list = new ArrayList<>();
        try {
            list = ExcelImportUtil.importExcel(multipartFile.getInputStream(),
                    SourceBaseUsecar.class, params);
        } catch (Exception e) {
            log.error("从文件读取数据错误:{}", e.getMessage());
        }

        SysCompany company = companyService.findById(companyId);
        List<SysDepartment> departments = departmentService.findDepartments(new HashMap<>());

        //删除旧数据
        if (importway == 1) {
            delete(companyId);
        }

        for (SourceBaseUsecar item : list) {
            item.setCompanyId(companyId);
            item.setCompanyName(company.getFullName());
            if (item.getTimeStart() == null) {
                continue;
            }
            item.setKjnd(DateUtil.getYear(item.getTimeStart()));
            Optional<SysDepartment> first = departments.stream().filter(t -> t.getName().equals(item.getDepartmentName())).findFirst();
            if (first.isPresent()) {
                item.setDepartmentId(first.get().getId());
            }
            sourceBaseUsecarDao.save(item);
        }
        return list.size();
    }

    //计算目的区域类型    中心城区内，中心城区外 ，  难以区分
    private String setAreaCategory(String placeEnd) {
        String area = "";
        //目的地包含'天河'、'越秀'、'荔湾'、'海珠'关键字归类为'中心城区内'
        if (placeEnd.contains("天河") || placeEnd.contains("越秀") || placeEnd.contains("荔湾") || placeEnd.contains("海珠")) {
            return "中心城区内";
        }
        //目的地包含'黄埔'、'南沙'、'从化'、'增城'、'花都'、'番禺'、'佛山'、'南海'、'钟落'、'东莞'、'白云.*国际机场'且不包含'黄埔大道'、'黄埔立交'关键字归类为'中心城区外'
        if ((placeEnd.contains("黄埔") || placeEnd.contains("南沙") || placeEnd.contains("从化") || placeEnd.contains("增城")
                || placeEnd.contains("花都") || placeEnd.contains("番禺") || placeEnd.contains("佛山") || placeEnd.contains("南海") || placeEnd.contains("东莞")
                || placeEnd.contains("白云") || placeEnd.contains("国际机场") && (!placeEnd.contains("黄埔大道") && !placeEnd.contains("黄埔立交")))) {
            return "中心城区外";
        }
        return "难以区分";
    }

    /**
     * 删除
     */
    public int delete(String companyId) {
        return sourceBaseUsecarDao.deleteByCompanyId(companyId);
    }

    /**
     * 查询记录
     *
     * @param id
     * @return
     */
    public SourceBaseUsecar findById(String id) {
        return sourceBaseUsecarDao.findById(id);
    }

    /**
     * 分页
     *
     * @param params
     * @return
     */
    public PageResult<SourceBaseUsecar> pageAll(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);

        List<SourceBaseUsecar> list = sourceBaseUsecarDao.findAll(params);
        PageInfo<SourceBaseUsecar> pageInfo = new PageInfo(list);

        return PageResult.<SourceBaseUsecar>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }

    /**
     * 列表
     *
     * @param params
     * @return
     */
    public List<SourceBaseUsecar> findAll(Map<String, Object> params) {
        return sourceBaseUsecarDao.findAll(params);
    }

    @Override
    public List<SourceBaseUsecar> findDepartmentData(Map<String, Object> params) {
        String[] departmentNames = params.containsKey("departmentNames") && StringUtil.isNotEmpty(params.get("departmentNames").toString()) ? params.get("departmentNames").toString().split(",") : null;
        if (departmentNames != null && departmentNames.length > 0) {
            params.put("departmentNames", departmentNames);
        }
        return sourceBaseUsecarDao.findDepartmentData(params);
    }

    @Override
    public List<SourceBaseUsecar> findMonthData(Map<String, Object> params) {
        return sourceBaseUsecarDao.findMonthData(params);
    }

    @Override
    public List<String> findCarNumberList(Map<String, Object> params) {
        return sourceBaseUsecarDao.findCarNumber(params);
    }

}
